<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
          :inline="true"
          ref="searchFromRef"
          :model="pm"
          class="searchForm"
      >
        <!-- 表单项 -->
<!--        数值通过下拉框的方式，从plants集合中取name-->
        <el-form-item label="植株名称：" style="width: 200px" prop="plantId">
          <el-select
              v-model="pm.plantId"
              placeholder="请选择植株名称"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="plant in plants"
                :key="plant.plantId"
                :label="plant.plantName"
                :value="plant.plantId"
            />
          </el-select>
        </el-form-item>
        <!-- 表单项 -->
        <el-form-item label="植株高度：" style="width: 200px" prop="plantHeight">
          <el-input placeholder="大于此高度的植物：" v-model="pm.plantHeight" />
        </el-form-item>
        <!-- 表单项 -->
        <el-form-item label="叶片数量：" style="width: 200px" prop="leafCount">
          <el-input placeholder="大于此叶片数量的植物：" v-model="pm.leafCount" />
        </el-form-item>
<!--        开花时间-->
        <el-form-item label="叶片数量：" style="width: 200px" prop="leafCount">
          <el-input placeholder="小于此开花时间的植物：" v-model="pm.leafCount" />
        </el-form-item>
        <!-- 表单项 -->
        <el-form-item label="测量者姓名：" style="width: 200px" prop="measuredBy">
          <el-input placeholder="请输入测量者姓名" v-model="pm.measuredBy" />
        </el-form-item>
      </el-form>

      <!-- 按钮 -->
      <el-button
          color="#909399"
          plain
          :icon="Search"
          @click="search"
          style="width: 75px"
      >查询</el-button
      >
      <el-button
          color="#e6a23c"
          plain
          :icon="Refresh"
          @click="resetSearch"
          style="width: 75px"
      >重置</el-button
      >
    </div>

    <!-- 操作区 -->
    <div class="action">
      <el-button
          color="#409eff"
          plain
          :icon="Plus"
          @click="add"
          style="margin-left: 10px"
      >录入表型</el-button
      >

      <!--      <el-button type="danger" plain :icon="Delete" @click="deleteAll"-->
      <!--      >批量删除</el-button-->
      <!--      >-->
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="plant-cards">
        <el-row :gutter="20">
          <el-col
              v-for="item in tableData"
              :key="item.phenotypeId"
              :xs="24"
              :sm="12"
              :md="6"
              :lg="6"
              class="card-col"
          >
            <el-card class="plant-card" :body-style="{ padding: '0px' }" shadow="hover">
              <!-- 图片区域 -->
              <div class="image-container">
                <img :src="item.plantInformation.imagePath" class="plant-image">
                <div class="plant-name-overlay">
                  <span class="plant-name">{{ item.plantInformation.plantName }}</span>
                </div>
              </div>

              <!-- 表型信息区域 -->
              <div class="phenotype-info">
                <el-descriptions :column="1" border size="small">
                  <el-descriptions-item label="植株高度">
                    {{ item.plantHeight }} 厘米
                  </el-descriptions-item>
                  <el-descriptions-item label="开花时间">
                    {{ item.floweringTime }} 天
                  </el-descriptions-item>
                  <el-descriptions-item label="叶片数量">
                    {{ item.leafCount }} 片
                  </el-descriptions-item>
                  <el-descriptions-item label="茎直径">
                    {{ item.stemDiameter }} 毫米
                  </el-descriptions-item>
                  <el-descriptions-item label="根长">
                    {{ item.rootLength }} 厘米
                  </el-descriptions-item>
                  <el-descriptions-item label="生长速率">
                    {{ item.growthRate }} 厘米/天
                  </el-descriptions-item>
                  <el-descriptions-item label="疾病抵抗等级">
                    <el-tag :type="getResistanceTagType(item.diseaseResistanceLevel)">
                      {{ item.diseaseResistanceLevel }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="应激耐受等级">
                    <el-tag :type="getToleranceTagType(item.stressToleranceLevel)">
                      {{ item.stressToleranceLevel }}
                    </el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <!-- 底部信息 -->
              <div class="bottom-info">
                <div class="measurement-info">
                  <el-tooltip
                      :content="formatDate(item.measurementDate)"
                      placement="top"
                  >
                    <div class="time-info">
                      <el-icon><Calendar /></el-icon>
                      {{ formatDate(item.measurementDate) }}
                    </div>
                  </el-tooltip>
                  <div class="measurer-info">
                    <el-icon><User /></el-icon>
                    测量人：{{ item.measuredBy }}
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="operations">
                  <el-button
                      type="primary"
                      :icon="Edit"
                      size="small"
                      class="edit-button"
                      @click="edit(item)"
                  >
                    编辑
                  </el-button>
                  <el-popconfirm
                      title="确认删除这条记录吗？"
                      @confirm="removeById(item)"
                  >
                    <template #reference>
                      <el-button
                          type="danger"
                          :icon="Delete"
                          size="small"
                          class="delete-button"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <!--      分页-->
      <div class="pagination">
        <el-pagination
            v-model:current-pageNum="pageInfo.pageNum"
            v-model:pageNum-size="pageInfo.size"
            :pageNum-sizes="[10, 15, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            background
            @change="paginate"
        />
      </div>
  </div>

  </div>
  <el-dialog
      v-model="show"
      :title="title"
      width="800"
      draggable
      :close-on-click-modal="false"
      @close="close"
      class="phenotype-dialog"
  >
    <el-form
        ref="sfRef"
        :model="pfm"
        :rules="rules"
        label-width="160"
        class="phenotype-form"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="植物名称" prop="plantId">
            <el-select
                v-model="pfm.plantId"
                placeholder="请选择植物名称"
                class="w-full"
            >
              <el-option
                  v-for="item in plants"
                  :key="item.plantId"
                  :label="item.plantName"
                  :value="item.plantId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="植株高度" prop="projectLeaderId">
            <el-input
                v-model="pfm.projectLeaderId"
                placeholder="请输入植株高度"
            >
              <template #append>厘米</template>
            </el-input>
          </el-form-item>

          <el-form-item label="开花时间" prop="floweringTime">
            <el-input
                v-model="pfm.floweringTime"
                placeholder="请输入开花时间"
            >
              <template #append>天</template>
            </el-input>
          </el-form-item>

          <el-form-item label="叶片数量" prop="leafCount">
            <el-input
                v-model="pfm.leafCount"
                placeholder="请输入叶片数量"
            >
              <template #append>片</template>
            </el-input>
          </el-form-item>
          <el-form-item label="应激耐受等级" prop="stressToleranceLevel">
            <el-select
                v-model="pfm.stressToleranceLevel"
                placeholder="请选择应激耐受等级"
                class="w-full"
            >
              <el-option label="耐受高" value="耐受高" />
              <el-option label="耐受中" value="耐受中" />
              <el-option label="耐受低" value="耐受低" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">

          <el-form-item label="茎直径" prop="stemDiameter">
            <el-input
                v-model="pfm.stemDiameter"
                placeholder="请输入茎直径"
            >
              <template #append>毫米</template>
            </el-input>
          </el-form-item>

          <el-form-item label="根长" prop="rootLength">
            <el-input
                v-model="pfm.rootLength"
                placeholder="请输入根长"
            >
              <template #append>厘米</template>
            </el-input>
          </el-form-item>

          <el-form-item label="生长速率" prop="growthRate">
            <el-input
                v-model="pfm.growthRate"
                placeholder="请输入生长速率"
            >
              <template #append>厘米/天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="疾病抵抗等级" prop="diseaseResistanceLevel">
            <el-select
                v-model="pfm.diseaseResistanceLevel"
                placeholder="请选择疾病抵抗等级"
                class="w-full"
            >
              <el-option label="抗病高" value="抗病高" />
              <el-option label="抗病中" value="抗病中" />
              <el-option label="抗病低" value="抗病低" />
            </el-select>
          </el-form-item>


        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 录入表型 对话框 -->
</template>

<script setup>
import phenotypicDataApi  from "@/api/PhenotypicDataApi";
import plantInformationApi  from "@/api/PlantApi";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";

// 获取全部的植物信息
const plants = ref([]);
plantInformationApi.findAll(1,99).then((result) => {
  plants.value = result.data.records;
});

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});
//响应式对象
const tableData = ref([]);
function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = pm.value; // 查询条件

  phenotypicDataApi
      .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
      .then((result) => {
        if (result.code == 200) {
          tableData.value = result.data.records;
          pageInfo.value.total = result.data.total;
          pageInfo.value.pageNum = result.data.pages;
          pageInfo.value.size = result.data.size;
        }
      });
}

// 搜索条表单双向数据绑定
const pm = ref({
  plantId: "",
  plantHeight: "",
  floweringTime: "",
  leafCount:"",
  diseaseResistanceLevel: "",
  stressToleranceLevel: "",
  measurementDate: "",
  measuredBy: "",
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.projectId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      phenotypicDataApi
          .removeAll(ids)
          .then((resp) => {
            if (resp.code == 200) {
              ElMessage({
                type: "success",
                message: "删除成功",
              });
              search(); //刷新
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除操作取消",
            });
          });
    });
  }
}
//  按id删除
function removeById(row) {
  let plant = toRaw(row);
  deleteById([plant.projectId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const plainFormModel = ref({
  plantId:"",
  plantHeight: "",
  floweringTime: "",
  leafCount: "",
  stemDiameter:"",
  rootLength:"",
  growthRate: "",
  diseaseResistanceLevel: "",
  stressToleranceLevel: ""
});
// 对话框内容别名
const pfm = plainFormModel;

// 对话框标题
const title = ref("新增表型信息");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增表型信息";
  let project = pfm.value;
  project.projectId = "";
}
// 提交表单
function submitForm() {
  let project = pfm.value;
  if (project.projectId !== "" ) {
    //修改
    submitEdit(project);
  } else {
    //录入表型
    submitAdd(project);
  }
}

// 新增逻辑
function submitAdd(project) {
  phenotypicDataApi.save(project).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let plant = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, plant);
  show.value = true;
  title.value = "修改表型信息";
  // 下一个时间滴答中赋值
  nextTick(() => {
    pfm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(project) {
  phenotypicDataApi.update(project).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let project = toRaw(row);
  user.locked = user.locked === true ? 0 : 1;
  phenotypicDataApi.updataByState(project).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      // project.locked = project.locked === 0 ? 1 : 0;
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
}

//头像上传成功时的回调函数
function avatarSuccess(resp, file) {
  if (resp.code == 200) {
    pfm.value.imagePath = resp.data;
  }
}

// 定义自定义验证规则：开始时间必须大于当前时间
const validateStartTime = (rule, value, callback) => {
  const now = dayjs().format("YYYY-MM-DD");
  if (value && dayjs(value).isBefore(now)) {
    callback(new Error("开始时间必须大于当前时间"));
  } else {
    callback();
  }
};

// 定义自定义验证规则：开始时间不能大于结束时间
const validateEndTime = (rule, value, callback) => {
  const startTime = pfm.value.projectStartTime;
  if (startTime && value && dayjs(startTime).isAfter(value)) {
    callback(new Error("开始时间不能大于结束时间"));
  } else {
    callback();
  }
};
// 表单验证规则
const rules = {
  projectName: [
    {
      required: true,
      message: '请输入表型名称',
      trigger: 'blur',
    },
  ],
  projectStartTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
    },
    { validator: validateStartTime, trigger: 'change' },
  ],
  projectEndTime: [
    {
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
    },
    { validator: validateEndTime, trigger: 'change' },
  ],
  projectStatus: [
    {
      required: true,
      message: '请选择项目状态',
      trigger: 'change',
    },
  ],
  studentParticipationCount: [
    {
      required: true,
      message: '请输入表型人数',
      trigger: 'blur',
    },
  ],
};


// Props 定义
defineProps({
  tableData: {
    type: Array,
    required: true
  }
})

// 获取疾病抵抗等级对应的标签类型
const getResistanceTagType = (level) => {
  const types = {
    '抗病高': 'success',
    '抗病中': 'warning',
    '抗病低': 'danger'
  }
  return types[level] || 'info'
}

// 获取应激耐受等级对应的标签类型
const getToleranceTagType = (level) => {
  const types = {
    '耐受强': 'success',
    '耐受中': 'warning',
    '耐受弱': 'danger'
  }
  return types[level] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
}

</script>

<style scoped>

.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


.avatar {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
}

.avatar .icon {
  width: 120px;
  height: 120px;
}

.avatar .preview {
  width: 120px;
  height: 120px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}


.project-details span {
  display: block;
  margin-bottom: 5px;
}

.project-details .participation {
  display: inline-block;
  font-size: 15px;
  margin-right: 10px; /* 可选：添加间距 */
}

.project-details .date-time {
  font-size: 14px; /* 字体小一点 */
  color: #999; /* 颜色浅一点 */
}

.plant-card {
  margin-bottom: 20px;
  /* 进一步减小整体高度 */
  max-height: 620px;
  min-height: 560px;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
}


.plant-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.image-container {
  position: relative;
  /* 稍微减小图片区域高度 */
  height: 180px;
  overflow: hidden;
  flex-shrink: 0;
}

.plant-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.plant-name-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));
  padding: 12px; /* 稍微减小内边距 */
  transform: translateY(0);
  transition: all 0.3s ease;
}

.plant-name {
  display: block;
  color: white;
  font-size: 18px; /* 稍微调小字体 */
  font-weight: 600;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  transform: translateY(0);
  transition: all 0.3s ease;
}

.phenotype-info {
  padding: 12px;
  flex: 1;
  overflow-y: auto;
  background-color: #fff;
  /* 调整描述信息区域高度 */
  min-height: 300px;
  max-height: 340px;
}

.bottom-info {
  padding: 8px 12px; /* 减小上下内边距 */
  border-top: 1px solid #ebeef5;
  background-color: #f8f9fa;
  /* 减小底部区域高度 */
  min-height: 80px;
  flex-shrink: 0;
}

.measurement-info {
  margin-bottom: 8px; /* 减小与按钮的间距 */
}

.time-info, .measurer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 13px;
  margin-bottom: 2px; /* 减小信息项之间的间距 */
  transition: color 0.3s ease;
}

.operations {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 4px; /* 减小与上方信息的间距 */
}

:deep(.el-descriptions__cell) {
  padding: 6px !important; /* 减小单元格内边距 */
}

:deep(.el-descriptions__label) {
  background-color: #f5f7fa;
  font-weight: 600;
  width: 100px;
  font-size: 13px; /* 调整标签字体大小 */
}

:deep(.el-descriptions__content) {
  min-width: 100px;
  font-size: 13px; /* 调整内容字体大小 */
}

/* 保持滚动条样式不变 */
.phenotype-info::-webkit-scrollbar {
  width: 6px;
}

.phenotype-info::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.phenotype-info::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.phenotype-info::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 对话框 */
.phenotype-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }
}

.phenotype-form {
  /* 设置表单最大宽度并居中 */
  max-width: 720px;
  margin: 0 auto;
}

/* 统一输入框和选择框宽度 */
:deep(.el-input),
:deep(.el-select) {
  width: 100%;
}

/* 美化表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 统一标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 美化底部按钮区域 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 10px;
}

.dialog-footer .el-button {
  min-width: 100px;
}

/* 输入框后缀单位样式 */
:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  color: #909399;
  font-size: 13px;
}

/* 统一下拉选择框样式 */
:deep(.el-select .el-input__wrapper) {
  width: 100%;
}

/* 调整行间距 */
.el-row {
  row-gap: 0;
}

/* 确保列之间有合适的间距 */
:deep(.el-col) {
  padding: 0 12px;
}

/* 美化输入框样式 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style>
